<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="UTF-8" />
        <title>14_鼠标拖拽-基本模板</title>
        <style>
            * {
                margin: 0;
                padding: 0;
            }

            div {
                position: absolute;
                width: 100px;
                height: 100px;
                background-color: aqua;
            }


        </style>
    </head>
    <body>
        <div></div>
        <script>
            var div = document.querySelector('div');

            div.onmousedown = function(event){
                // 获取盒子的偏移量
                var eleX = div.offsetLeft;
                var eleY = div.offsetTop;

                // 获取鼠标的起始位置
                var startX = event.clientX;
                var startY = event.clientY;

                div.onmousemove = function(event){
                    // 获取鼠标的结束位置
                    var endX = event.clientX;
                    var endY = event.clientY;

                    // 鼠标移动的距离差
                    var disX = endX - startX;
                    var disY = endY - startY;

                    // 获取盒子的最终位置
                    var lastX = eleX + disX;
                    var lastY = eleY + disY;

                    div.style.left = lastX + 'px';
                    div.style.top = lastY + 'px';
                }

            }


            div.onmouseup = function(){
                div.onmousemove  =  null;
            }
        </script>
    </body>
</html>